/** 用户登录服务 **/
const httpUtil = require('../utils/http.util.js')
/**
 * 验证服务端当前session是否有效
 */
const sessionCheck = function (options) {
  var app = options.app;
  httpUtil.get({
    url: app.globalData.apiServerUrl + "/wechat/user/checkSession",
    success: res => {
      if (res) {
        // 后台session有效
        if (options.valid) {
          options.valid();
        }
      } else {
        // 后台session无效
        if (options.invalid) {
          options.invalid();
        }
      }
    }
  });
}

/**
 * 通过code换取用户注册、绑定信息，如果未注册，返回null
 */
const login = function (options) {
  var app = options.app; 
  httpUtil.get({
    url: app.globalData.apiServerUrl + "/wechat/user/login",
    data: {code: options.code},
    original: true,
    success: res => {
      if (res) {
        //登录成功
        var cookie = res.header['Set-Cookie'];
        updateCookie({ app: app, cookie: cookie });
        updateUser({ app: app, user: res.data.data });
        if(options.success){
          options.success(res.data.data);
        }
      }
    }
  });
};

/**
 * 提取Storage中的用户信息与Cookie信息到globalData中
 */
const restoreUser = function (options) {
  var app = options.app;
  var user = wx.getStorageSync('user');
  app.globalData.user = user;
}

/**
 * 提取Storage中的Cookie信息到globalData中
 */
const restoreCookie = function (options) {
  var app = options.app;
  var cookie = wx.getStorageSync('Cookie');
  app.globalData.requestHeader.Cookie = cookie;
}

/**
 * 清理Storage和globalData中的用户信息
 */
const clearUser = function (options) {
  var app = options.app;
  wx.clearStorageSync('user');
  app.globalData.user = null;
}
/**
 * 清理Storage和globalData中的Cookie信息
 */
const clearCookie = function (options) {
  var app = options.app;
  wx.clearStorageSync('Cookie');
  app.globalData.requestHeader.Cookie = null;
}
/**
 * 更新Storage和globalData中的用户信息
 */
const updateUser = function (options) {
  var app = options.app;
  app.globalData.user = options.user;
  wx.setStorageSync('user', options.user);
}
/**
 * 更新Storage和globalData中的Cookie信息
 */
const updateCookie = function (options) {
  var app = options.app;
  app.globalData.requestHeader.Cookie = options.cookie;
  wx.setStorageSync('Cookie', options.cookie);
}

module.exports = {
  restoreUser: restoreUser,
  restoreCookie: restoreCookie,
  clearCookie: clearCookie,
  clearUser: clearUser,
  sessionCheck: sessionCheck,
  login: login
}